﻿using System;
using System.Collections.Generic;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Windows.Forms;
using iSun.ServerFile;
using System.Configuration;
using System.IO;
using iSun.Entity;

namespace UpLoadConsoleApplication
{
    public static class DataAction
    {
        public static void ModifyConfig()
        {
           
        }

        public static void UpdateAppConfig(string newKey, string newValue)
        {
            bool isModified = true;
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == newKey) { isModified = true; }
            }       // Open App.Config of executable     
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            // You need to remove the old settings object before you can replace it   
            if (isModified) { config.AppSettings.Settings.Remove(newKey); }
            // Add an Application Setting.  
            config.AppSettings.Settings.Remove(newKey);
            config.AppSettings.Settings.Add(newKey, newValue);
            // Save the changes in App.config file.   
            config.Save(ConfigurationSaveMode.Modified);
            // Force a reload of a changed section.     
            ConfigurationManager.RefreshSection("appSettings");

        } 
        
        public static void Rename(string oldName, string newName)
        {

        }

        public static void MoveFile(string SN,out int flag)
        {
            flag = 0;
            string __path = ConfigurationManager.AppSettings["defualtSourceFilePath"];
            DirectoryInfo dir = new DirectoryInfo(__path);
            FileInfo[] __files = dir.GetFiles(); 
            foreach(FileInfo file in __files)
            {
                if (SN.Length > 36) {
                    string[] _strArr =  SN.Split('_');
                    string __SN = _strArr[1];
                    string __type = _strArr[2];
                    string __newPath = ConfigurationManager.AppSettings["filePath"];
                    __newPath = __newPath + __SN + "\\";
                    string __ttype = "";
                    switch (__type)
                    {
                        case "0":
                            __newPath = __newPath +"images\\";
                            __ttype = "P";
                            break;
                        case "1":
                            __newPath =  __newPath+"thumb\\";
                            __ttype = "T";
                            break;
                        case "2":
                            __newPath = __newPath + "vedio\\";
                            __ttype = "V";
                            break;
                        default:
                            __newPath = __newPath + "images\\";
                            __ttype = "P";
                            break;
                    }
                    file.MoveTo(__newPath + __SN + "_" + __ttype + "_" + file.Name);
                    flag = 1;
                }
            }
            
            string path = ConfigurationManager.AppSettings["filePath"];// : ConfigurationManager.AppSettings["filePath1"];
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            uFile(path, channel, 0);
        }


        /// <summary>
        /// 生成相关目录
        /// </summary>
        /// <param name="SN"></param>
        public static void CreateProductDir(string SN)
        {
            string __path = ConfigurationManager.AppSettings["filePath"];
            if (!Directory.Exists(__path + SN))
            {
                Directory.CreateDirectory(__path + SN);
                Directory.CreateDirectory(__path + SN + "\\images");
                Directory.CreateDirectory(__path + SN + "\\thumb");
                Directory.CreateDirectory(__path + SN + "\\vedio");
            }
        }


        public static void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
        {
            float percent = 0;
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);
                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                    //label1.Text = "当前补丁下载进度" + percent.ToString() + "%";
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码，否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception)
            {
                throw;
            }
        }

        public static void DownLandHttpFile(string filePath)
        {
            // Create a request for the URL. 	
            string __URLpath = ConfigurationManager.AppSettings["SeverURL"];
            WebRequest request = WebRequest.Create(__URLpath+filePath);

            string __path = ConfigurationManager.AppSettings["filePath"];

            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Display the status.
            Console.WriteLine(response.StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content. 
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Cleanup the streams and the response.
            reader.Close();
            dataStream.Close();
            response.Close();
        }

        public static void DownLandFile(string SN, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1, System.Windows.Forms.Label label2)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            BasicHttpBinding binding2 = new BasicHttpBinding();
            binding2.TransferMode = TransferMode.Streamed;

            IList<string> _filelist = channel.GetSNFiles(SN);
            foreach (string __files in _filelist)
            {
                string __path = ConfigurationManager.AppSettings["filePath1"]+SN;
                string filePath = __path + __files;

                string[] ___path = filePath.Split('\\');
                string ___dir = filePath.Replace(___path[___path.Length - 1], "");
                if (!Directory.Exists(___dir))
                {
                    Directory.CreateDirectory(___dir);
                }
                label2.Text = __files;
                string url = ConfigurationManager.AppSettings["SeverURL"]+ "upload/photo/"+SN+__files.Replace('\\','/');
                DownloadFile(url, filePath, prog, label1);
            }
        }

        public static void DownLandFile()
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            BasicHttpBinding binding2 = new BasicHttpBinding();
            binding2.TransferMode = TransferMode.Streamed;

            IList<string> _filelist = channel.GetFiles();
            foreach (string __files in _filelist)
            {
                iSun.DownloadRequest request = new iSun.DownloadRequest();
                request.FileName = __files;
                iSun.FileUploadMessage __Data = channel.GetProduct(request);
                string __path = ConfigurationManager.AppSettings["filePath"];
                string filePath = __path + __files;

                string[] ___path = filePath.Split('\\');
                string ___dir = filePath.Replace(___path[___path.Length - 1], "");
                if (!Directory.Exists(___dir))
                {
                    Directory.CreateDirectory(___dir);
                }

                FileStream targetStream = null;
                using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    //read from the input stream in 4K chunks
                    //and save to output stream
                    const int bufferLen = 4096;
                    byte[] buffer = new byte[bufferLen];
                    int count = 0;
                    while ((count = __Data.FileData.Read(buffer, 0, bufferLen)) > 0)
                    {
                        targetStream.Write(buffer, 0, count);
                    }
                    targetStream.Close();
                    __Data.FileData.Close();
                    //stream(entity);
                }
            }
        }

        public static void UploadSourceFile(int stepN)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            BasicHttpBinding binding2 = new BasicHttpBinding();
            binding2.TransferMode = TransferMode.Streamed;
            string path = stepN == 0 ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"];
            if (stepN == 0)
            {
                DirectoryInfo dir = new DirectoryInfo(path);
                IList<ProductPhotoEnitty> list = new List<ProductPhotoEnitty>();
                foreach (DirectoryInfo _dir in dir.GetDirectories())
                {
                    ProductPhotoEnitty pEntity = new ProductPhotoEnitty();
                    pEntity.SN = _dir.Name;
                    pEntity.ProductName = _dir.Name;
                    pEntity.ID = new Guid();
                    list.Add(pEntity);
                }
                channel.UploadProduct(ZX.Common.Globals.ListToJson<ProductPhotoEnitty>(list));
            }
            using (channel as IDisposable)
            {
                uFile(path, channel,stepN);
            }

        }


        public static void SetFlag(string SN, string Flag)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            channel.SetFlag(SN, Flag);
            MessageBox.Show("设置成功");
        }

        public static void DeleteImages(string imagesPath)
        {
            iSun.UpLoadServiceClient ser = new iSun.UpLoadServiceClient();
            iSun.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
            channel.DeleteProuctImages(imagesPath);
        }
    
        static void uFile(string path, iSun.IUpLoadService channel,int stepN)
        {
            DirectoryInfo dir = new DirectoryInfo(path);

            FileInfo[] allFile = dir.GetFiles();
            foreach (FileInfo fi in allFile)
            {
                if(fi.Name.StartsWith("Uploaded_"))
                {
                    continue;
                }
                string _path = stepN == 0 ? ConfigurationManager.AppSettings["filePath"] : ConfigurationManager.AppSettings["filePath1"];
                ProductImage entity = new ProductImage();
               
                entity.fileName = fi.Name;
                entity.FilePath = fi.FullName.Replace(_path, "").Replace(fi.Name,"");
                entity.SN = entity.FilePath.Split('\\')[0];
                entity.DirectoryName = fi.DirectoryName.Replace(_path, "");
                
                entity.StepN = stepN;
                
                entity.SourceFileName = fi.Name;
                entity.FileType = fi.Extension;

                entity.ImageType = "0";
                entity.ImageType = entity.FilePath.Contains("\\thumb\\") ? "1" : entity.ImageType;
                entity.ImageType = entity.FilePath.Contains("\\vedio\\") ? "2" : entity.ImageType;
                //entity.ImageType = 
                if (fi.Extension.ToLower().IndexOf("jpg") > -1)
                {
                    Fotofly.JpgPhoto jpgPhotoOne = ZX.Common.IPTC.ReadImageInfo.Load(fi.FullName);
                    entity.Summary = jpgPhotoOne.Metadata.Comment;
                    entity.CreationSoftware = jpgPhotoOne.Metadata.CreationSoftware;
                    entity.CameraManufacturer = jpgPhotoOne.Metadata.CameraManufacturer;
                    entity.CameraModel = jpgPhotoOne.Metadata.CameraModel;
                    entity.Copyright = jpgPhotoOne.Metadata.Copyright;
                    entity.HeigthPix = jpgPhotoOne.Metadata.ImageHeight;
                    entity.WidthPix = jpgPhotoOne.Metadata.ImageWidth;
                }
                string json = ZX.Common.Globals.ObjectToJSON(entity);

                iSun.FileUploadMessage file = new iSun.FileUploadMessage();
                file.SavePath = json;
                file.FileName = fi.Name;// "IMG_0467.jpg";
                file.FileData = new FileStream(fi.FullName, FileMode.Open);

                //UpLoadService.FileUploadMessage request = new UpLoadService.FileUploadMessage();
                //request.FileName = FileUpload1.FileName;
                //request.SavePath = "ooooooo";
                //request.FileData = FileUpload1.FileContent;
                //UpLoadService.IUpLoadService channel = ser.ChannelFactory.CreateChannel();
                channel.UploadFile(file);
                //channel.UploadFile(file);
                file.FileData.Close();
                //fi.Decrypt
                try
                {
                    fi.MoveTo(fi.FullName.Replace(fi.Name, "") + "Uploaded_" + fi.Name);
                }catch(Exception e){
                }
            }
            foreach (DirectoryInfo _dir in dir.GetDirectories())
            {
                uFile(_dir.FullName, channel,stepN);
            }
        }
    }






    public static class DataManager
    {
        #region 私有变量
        static IFilesService channel;
        static string baseAddress = "http://localhost:12251/";
        #endregion

        #region 属性
        public static string BaseAddress
        {
            get { return baseAddress; }
            set
            {
                channel = null;
                baseAddress = value;
            }
        }

        public static IFilesService Channel
        {
            get
            {
                if (channel == null)
                {
                    WebHttpBinding binding = new WebHttpBinding() { TransferMode = TransferMode.Streamed, MaxReceivedMessageSize = 2147483647 };
                    binding.Security.Mode = WebHttpSecurityMode.None;
                    EndpointAddress address = new EndpointAddress(new Uri(baseAddress));
                    var channelFactory = new ChannelFactory<IFilesService>(binding, address);
                    channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior() { DefaultBodyStyle = System.ServiceModel.Web.WebMessageBodyStyle.Wrapped, FaultExceptionEnabled = true });
                    channel = channelFactory.CreateChannel();
                }
                return channel;
            }
        }
        #endregion

        public static void SetControlText(Control col, string text)
        {
            if (col.InvokeRequired && col.IsHandleCreated)
                col.BeginInvoke(new Action<Control, string>(SetControlText), col, text);
            else
                col.Text = text;
        }
    }
}
